// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------
const path = require('path');
const fs = require('fs');
module.exports = class extends think.cmswing.center {
  constructor(ctx) {
    super(ctx);
    this.pdb = this.model('ext_attachment_pic');
    this.fdb = this.model('ext_attachment_file');
  }
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html
    return this.display();
  }
  // 上传图片
  async uploadpicAction() {
    const type = this.get('type');
    let name = 'data';
    let att = {};
    if (!think.isEmpty(type)) {
      const atts = await this.extModel('attachment').where({dis: type, type: 0}).find();
      att = think.extend(att, atts);
    }
    if (!think.isEmpty(att) && !think.isEmpty(att.name)) {
      name = att.name;
    }

    const file = think.extend({}, this.file(name));
    //console.log("+++++++++file="+JSON.stringify(file));
    const filepath = file.path;
    //console.log("+++++++++filepath="+filepath);
    const extname = path.extname(file.name);
    //console.log("+++++++++extname="+extname);
    const basename = path.basename(filepath) + extname;
    //console.log("+++++++++basename="+basename);
    // console.log(basename);
    const ret = {'status': 1, 'info': '上传成功', 'data': ''};
    let data;
      // 默认路径
      const uploadPath = this.saveFile(filepath, 'picture', basename, att);
      //console.log("+++++++++uploadPath="+JSON.stringify(uploadPath));
      // 返回最新路径
      file.path = uploadPath.path + '/' + basename;
      //console.log("+++++++++file.path="+file.path);
      if (think.isFile(file.path)) {
        data = {
          path: uploadPath.root + '/' + basename,
          create_time: new Date().getTime(),
          status: 1
        };
        // 添加水印
        if (att.mark == 1) {
          const mark = this.extService('mark', 'attachment');
          mark.mark(file.path);
        }
      } else {
        console.log('not exist');
      }


    // 添加文件并返回结果
    //console.log("+++++++++data="+JSON.stringify(data));
    const res = await this.pdb.add(data);
    //console.log("+++++++++res="+res);
    const r = {id: res, url: await get_pic(res), name: (file.name).trim()};
    let rr = {};
    if (!think.isEmpty(att) && !think.isEmpty(att.rule)) {
      const match = att.rule.match(/\${(\S+?)\}/g);
      // console.log(match);
      const replace = [];
      for (let val of match) {
        val = val.replace(/(^\${)|(\}$)/g, '');
        replace.push(r[val]);
      }
      // console.log(replace);
      rr = str_replace(match, replace, att.rule);
      // console.log(rr);
      if (att.rule.indexOf('{') === 0) {
        rr = JSON.parse(rr);
      }
    }
    return think.isEmpty(rr) ? this.json(res) : this.json(rr);
  }
  // 转移文件
  saveFile(filepath, defpath, basename, attr) {
    // 处理路径
    if (!think.isEmpty(attr.path)) {
      defpath = attr.path;
    };
    // 生成目录
    const rootpath = `/upload/${defpath}/${dateformat('Y-m-d', new Date().getTime())}`;
    const uploadPath = `${think.resource}${rootpath}`;
    think.mkdir(uploadPath);
    // 转移文件
    if (think.isFile(filepath)) {
      fs.renameSync(filepath, uploadPath + '/' + basename);
    }
    return {
      path: uploadPath,
      root: rootpath,
      def: defpath
    };
  }

  // 添加
  async qiniuaddAction() {
    const post = this.post();
    const data = {
      create_time: new Date().getTime(),
      name: post.key,
      savename: post.key,
      mime: post.mime,
      size: post.size,
      type: 2,
      sha1: post.hash,
      md5: think.md5(post.id)
    };
    // console.log(data);
    const res = await this.model('ext_attachment_file').add(data);
    return this.json(res);
  }

};
